# 根据cve_id 进行分析
import sqlite3
import sys
sys.path.append('..')
import dao.AnalysisDao as AnalysisDao
import service.CIService as CIService
import service.GiteeService as GiteeService
# 从配置文件中读取数据库路径
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
db_path = config.get('database', 'path')
def analyzeCI(cve_id):
    with sqlite3.connect(db_path) as conn:
        # if AnalysisDao.is_already_analyze(conn, cve_id, AnalysisDao.AnalysisType.CI):
            # print("{} 已经分析过了, 结论是：{}\n".format(cve_id, str(AnalysisDao.get_analysis(conn, cve_id, AnalysisDao.AnalysisType.CI))))
            # return AnalysisDao.get_analysis(conn, cve_id, AnalysisDao.AnalysisType.CI)
        tAndR = CIService.getTypeAndReason(cve_id)
        # print(cve_id, tAndR)
        t = tAndR['type']
        r = tAndR['reaseon']
        comment = ""
        if t is not None:
            comment = str(t)
            if r is not None:
                comment += "，" + str(r)
        AnalysisDao.update_analysis(conn, cve_id, AnalysisDao.AnalysisType.CI, True, comment)
        return comment
    
def analyzeCIWithoutCache(cve_id):
    tAndR = CIService.getTypeAndReason(cve_id)
    t = tAndR['type']
    r = tAndR['reaseon']
    s = tAndR['processStage']
    comment = ""
    if t is not None:
        # comment = str(t)
        if t == '误报':
            comment = str(t)
        elif t == '有效漏洞':
            comment = str(s)
        else:
            comment = str(t)
        if r is not None:
            comment += "，" + str(r)
    else:
        comment = "{} 没有CI信息".format(cve_id)
    return comment
    
def analyzeGiteeWithoutCache(cve_id):
        info = ""
        historyList = GiteeService.getHistoryIssueList(cve_id)
        if len(historyList) == 0:
            info = "{} 没有历史issue".format(cve_id)
        else:
            for item in GiteeService.getHistoryIssueList(cve_id):
                info = info + str(item) 
        return info

def analyzeGitee(cve_id):
    with sqlite3.connect(db_path) as conn:
        info = ""
        if AnalysisDao.is_already_analyze(conn, cve_id, AnalysisDao.AnalysisType.GITEE):
            print("{} 已经分析过了, 结论是：{}\n".format(cve_id, str(AnalysisDao.get_analysis(conn, cve_id, AnalysisDao.AnalysisType.GITEE))))
            return
        historyList = GiteeService.getHistoryIssueList(cve_id)
        if len(historyList) == 0:
            print("{} 没有历史issue\n".format(cve_id))
        else:
            for item in GiteeService.getHistoryIssueList(cve_id):
                info += str(item) + "\n"
                print(item)
    AnalysisDao.update_analysis(conn, cve_id, AnalysisDao.AnalysisType.GITEE, True, info.strip())

def getGiteeAnalysis(cve_id):
    with sqlite3.connect(db_path) as conn:
        return AnalysisDao.get_analysis(conn, cve_id, AnalysisDao.AnalysisType.GITEE).strip()